<?php

namespace Home\Controller;

use Think\Controller;

class LoginController extends Controller
{
    //登陆主页
    public function index()
    {
        $list = M('list')->where("1=1")->order('create_time DESC')->limit('12')->select();
        $this->list = $list;
        $this->display();
    }

    public function jubao_act()
    {

        if (IS_POST) {
            $hebing = M("Jubao");
            $arEmail = trim(I('post.arEmail'));
            $arType = trim(I('post.arType'));
            $arContent = trim(I('post.arContent'));
            $appid = (int)$_POST['appid'];

            //$member = M("Member");
            //$result = $member->where(array('id'=>session('homeId')))->find();
            if (!$arEmail) {
                $this->error("Email不能为空");
                exit;
            }
            if (!$arContent) {
                $this->error("举报内容不能为空");
                exit;
            }
            $data = array();
            $data['appid'] = $appid;
            $data['addtime'] = date('Y-m-d H:i:s', time());
            $data['email'] = $arEmail;
            $data['reason'] = $arType;
            $data['note'] = $arContent;
            $hebing->add($data);

            $this->success("举报成功");

        } else {
            $this->error("请不要恶意提交");
        }
    }

    public function denglu()
    {
        $this->display();
    }

    public function nopage()
    {
        //热门
        $list = M('list')->where("ishot=1")->order('id DESC')->limit('12')->select();
        $articles = M('Articles')->limit(4)->where("startTime < now() and now() < endTime and spare1 = 1 ")->order('rand()')->select();
        $this->articles=$articles;
        $this->list = $list;
        $this->display();
    }

    public function zhuce()
    {
        $this->display();
    }

    public function forgotpwd()
    {
        $this->display();
    }

    //登陆验证
    public function login()
    {
        if (!IS_POST) $this->error("非法请求");
        $member = M('member');
        $username = I('username');
        $password = I('password', '', 'md5');

        if (filter_var($username, FILTER_VALIDATE_EMAIL)) {
            // $user = $member->where(array('username' => $username, 'password' => $password))->find();
            $user = $member->where(array('username' => $username))->find();
        } else {
            $user = $member->where(array('phone' => $username, 'password' => $password))->find();
        }
        //$code = I('verify','','strtolower');
        /*
        //验证验证码是否正确
        if(!($this->check_verify($code))){
            $this->error('验证码错误');
        }
        */
        //验证账号密码是否正确


        if (!$user) {
            $this->error('账号或密码错误');
        }


        if ($user['id'] !== '1') {
            //验证账户是否被禁用
            if ($user['status'] == 0) {
                $this->error('账号被禁用，请联系超级管理员 :(');
            }

            //验证账户是否已过期
            $create_time = $user['create_time'];
            $tianshu = $user['tianshu'];

            $dtime = strtotime(date("y-m-d h:i:s")); //当前时间
            $sjc = ceil(($dtime - $create_time) / 86400); //60s*60min*24h

            if ($sjc > $tianshu) {
                $this->error('您账号已过期，请联系超级管理员 :(');
            }
        }
        $nowmmdate = date('Ymd', time());
        //dd($user);die;
        //验证是否为管理员
        //更新登陆信息
        $data = array(
            'id' => $user['id'],
            'update_time' => time(),
            'freedate' => $nowmmdate,
            'login_ip' => get_client_ip(0, true),
        );
        if ($nowmmdate > $user['freedate']) {
            $config = M("Config")->find();
            if ($user['username']) {
                $everydaynum = $config['freedownnum1'];
            }
            if ($user['phone']) {
                $everydaynum = $config['freedownnum2'];
            }
            if ($user['username'] && $user['phone']) {
                $everydaynum = $config['freedownnum3'];
            }
            $data['everydaynum'] = $everydaynum;
        }
        //如果数据更新成功  跳转到后台主页
        if ($member->save($data)) {
            session('homeId', $user['id']);
            session('homename', $user['username']);

            $Ipaddress = M("Ipaddress");
            $Ipaddress->where(array('tid' => $user['id']))->delete();
            $this->success("登陆成功", U('Index/index'));
        }
        //定向之后台主页


    }

    //注册验证
    public function reg()
    {
        if (!IS_POST) $this->error("非法请求");
        //默认显示添加表单

        if (IS_POST) {
            $checkcode = I('checkcode');
            $config = M("Config")->find();
            $_POST['allowsize'] = $config['allowsize'];
            $_POST['singlesize'] = $config['singlesize'];
            $_POST['uptype'] = $config['uptype'];
            $_POST['tianshu'] = $config['tianshu'];
            $_POST['everydaynum'] = $config['freedownnum1'];
            $_POST['freedate'] = date('Ymd', time());
            //如果用户提交数据
            $model = D("Member");

            $username = I('username');
            if (strlen($username) > 25) {
                $this->error('此邮箱太长，请从新换一个邮箱！');
            }
            if ($checkcode != session('emailcode')) {
                $this->error('验证码不正确！');
            }

            if ($username != session('emailadd')) {
                $this->error('邮箱不正确！');
            }
            $todaytime = strtotime(date('Y-m-d', time()));
            $ip = get_client_ip();
            $mmcount = $model->where(" login_ip='" . $ip . "' and create_time>'" . $todaytime . "'")->count();
            if ($mmcount >= 5) {
                $this->error('同一IP地址一天最多可注册5个账号！');
            }
            //验证账号密码是否正确
            $user = $model->where(array('username' => $username))->find();

            if ($user) {
                $this->error('此邮箱已存在！');
            }
            $_POST['isggconfig'] = '1';
            if (!$model->create()) {
                // 如果创建失败 表示验证没有通过 输出错误提示信息
                $this->error($model->getError());
                exit();
            } else {
                if ($model->add()) {
                    $this->success("注册成功", U('login/index'));
                } else {
                    $this->error("注册失败");
                }
            }
        }
    }


    //注册验证
    public function regphone()
    {
        if (!IS_POST) $this->error("非法请求");
        //默认显示添加表单

        if (IS_POST) {
            $checkcode = I('checkcode88');
            $config = M("Config")->find();
            $_POST['allowsize'] = $config['allowsize'];
            $_POST['singlesize'] = $config['singlesize'];
            $_POST['uptype'] = $config['uptype'];
            $_POST['tianshu'] = $config['tianshu'];
            $_POST['everydaynum'] = $config['freedownnum2'];
            $_POST['freedate'] = date('Ymd', time());
            //如果用户提交数据
            $model = D("Member");

            $phone = I('phone');
            if (strlen($phone) != 11) {
                $this->error('请输入正确的手机号码！');
            }
            if ($checkcode != session('emailcode88')) {
                $this->error('验证码不正确！');
            }
            if ($phone != session('emailadd88')) {
                $this->error('手机号码不正确！');
            }
            $todaytime = strtotime(date('Y-m-d', time()));
            $ip = get_client_ip();
            $mmcount = $model->where(" login_ip='" . $ip . "' and create_time>'" . $todaytime . "'")->count();
            if ($mmcount >= 5) {
                $this->error('同一IP地址一天最多可注册5个账号！');
            }
            //验证账号密码是否正确
            $user = $model->where(array('phone' => $phone))->find();

            if ($user) {
                $this->error('此手机号码已存在！');
            }
            $_POST['isggconfig'] = '1';
            if (!$model->create()) {
                // 如果创建失败 表示验证没有通过 输出错误提示信息
                $this->error($model->getError());
                exit();
            } else {
                if ($model->add()) {
                    $this->success("注册成功", U('login/index'));
                } else {
                    $this->error("注册失败");
                }
            }
        }
    }


    //验证码
    public function verify()
    {
        ob_clean();
        $Verify = new \Think\Verify();
        $Verify->codeSet = '0123456789';
        $Verify->fontSize = 25;
        $Verify->length = 4;
        $Verify->useNoise = false;  // 关闭验证码杂点
        $Verify->entry();
    }

    protected function check_verify($code)
    {
        $verify = new \Think\Verify();
        return $verify->check($code);
    }

    public function logout()
    {
        session('homeId', null);
        session('homename', null);
        redirect(U('Login/index'));
    }

    public function chaxun()
    {
        //默认显示添加表单
        if (!IS_POST) {
            $this->display();
        }
        if (IS_POST) {
            //如果用户提交数据

            $udid = I('udid');
            if (empty($udid)) {
                $this->error("请正确输入udid");
            }

            $model = M("Post");
            $where['udid'] = $udid;
            $where['status'] = array('in', '1,2,3');
            $result = $model->where($where)->order('id desc')->find();
            if ($result) {
                if ($result['status'] == 3) {
                    $this->status = 3;
                    $this->pid = $result['pid'];
                    $this->web = $result['web'];
                    $this->udid = $udid;
                    $this->update_com = $result['update_com'];
                } else {
                    $this->status = '正在制作，请稍后!';
                }
            } else {
                $this->status = '没有您输入的UDID!';
            }
            $this->display();
        }
    }

    public function tw_chaxun()
    {
        //默认显示添加表单
        if (!IS_GET) {
            $this->display();
        }
        if (IS_GET) {
            //如果用户提交数据

            $udid = I('udid');
            if (empty($udid)) {
                $this->error("请正确输入udid");
            }

            $model = M("Post");
            $result = $model->where(array('udid' => $udid))->order('id desc')->find();
            if ($result) {
                if ($result['status'] == 3) {
                    $this->status = 3;
                    $this->uid = session('homeId');
                    $this->pid = $result['pid'];
                    $this->web = $result['web'];
                    $this->udid = $udid;
                    $this->update_com = $result['update_com'];
                } else {
                    $this->status = '正在制作，请稍后!';
                }
            } else {
                $this->status = '没有您输入的UDID!';
            }
            $this->display('chaxun');
        }
    }

    public function mmsendmail($post_data)
    {
        $url = 'http://www.trsoso.com/phpmail.php';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // post数据
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 2);
        // post的变量
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);

        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    public function sendemailcode()
    {

        //echo phpinfo();exit;
        $username = trim(I('post.username'));
        //$username = '54885782@qq.com';
        $member = M('Member');
        $result = $member->where(array('username' => $username))->find();
        if ($result) {
            $config = M("Config")->find();
            //echo "<pre>";print_r($config);
            $mycode = rand(100000, 999999);
            session('emailcode', $mycode);
            session('emailadd', $username);

            $address = $username;
            $Subject = '【找回密码】--' . $address;

            $message = '<html dir="ltr">' . "\n";
            $message .= '<head>' . "\n";
            $message .= '<title>【找回密码】</title>' . "\n";
            $message .= '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">' . "\n";
            $message .= '</head>' . "\n";
            $message .= '<body>';
            $message .= '<div style="width: 758px; font-family:Arial; margin:0 auto; border-color: #EBA858 #BABABA #BABABA;border-width: 7px 1px 1px;border-style: solid; font-size:14px;color:#6B6B6B;">';
            $message .= '<div style="padding:10px;">';
            $message .= '<p style=" font-weight:bold;font-size: 12px;height:24px;line-height:24px;">您的验证码是：' . $mycode . '（5分钟内有效），为了保证您的账户安全，请勿向任何人提供此验证码。<br />
感谢使悟空APP内测分发分发平台,官方网站:http://zjchcf.com 本邮件由系统自动发送，请勿直接回复.</p>';
            $message .= '</div>';
            $message .= '</div>';
            $message .= '</body>' . "\n";
            $message .= '</html>' . "\n";

            $post_data = array(
                'mail_host' => $config['mail_smtp'],
                'mail_account' => $config['mail_account'],
                'mail_pass' => $config['mail_pass'],
                'mail_port' => '25',
                'mail_name' => $config['mail_name'],
                'mail_subject' => $Subject,
                'mail_content' => $message,
                'mail_to' => $address,
                'pass' => '2077e4a6bafa9b4e7b55e1fff16818af',
            );

            $this->mmsendmail($post_data);

            $data['code'] = 1;
            $data['msg'] = '发送成功';
            $this->ajaxReturn($data, 'JSON');
            exit;
        } else {
            $data['code'] = 0;
            $data['msg'] = '该邮箱未注册';
            $this->ajaxReturn($data, 'JSON');
            exit;
        }

    }


    public function sendemailcode22()
    {

        $username = trim(I('post.username'));
        //$username = '54885782@qq.com';
        //$member = M('Member');
        //$result = $member->where(array('username'=>$username))->find();
        //if($result){
        if (1) {
            $config = M("Config")->find();
            $mycode = rand(100000, 999999);
            session('emailcode', $mycode);
            session('emailadd', $username);


            $address = $username;
            $Subject = '【验证码】--' . $address;

            $message = '<html dir="ltr">' . "\n";
            $message .= '<head>' . "\n";
            $message .= '<title>【验证码】</title>' . "\n";
            $message .= '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">' . "\n";
            $message .= '</head>' . "\n";
            $message .= '<body>';
            $message .= '<div style="width: 758px; font-family:Arial; margin:0 auto; border-color: #EBA858 #BABABA #BABABA;border-width: 7px 1px 1px;border-style: solid; font-size:14px;color:#6B6B6B;">';
            $message .= '<div style="padding:10px;">';
            $message .= '<p style=" font-weight:bold;font-size: 12px;height:24px;line-height:24px;">您的验证码是：' . $mycode . '（5分钟内有效），为了保证您的账户安全，请勿向任何人提供此验证码。<br />
感谢使悟空APP内测分发分发平台,官方网站:http://zjchcf.com 本邮件由系统自动发送，请勿直接回复.</p>';
            $message .= '</div>';
            $message .= '</div>';
            $message .= '</body>' . "\n";
            $message .= '</html>' . "\n";

            $post_data = array(
                'mail_host' => $config['mail_smtp'],
                'mail_account' => $config['mail_account'],
                'mail_pass' => $config['mail_pass'],
                'mail_port' => '25',
                'mail_name' => $config['mail_name'],
                'mail_subject' => $Subject,
                'mail_content' => $message,
                'mail_to' => $address,
                'pass' => '2077e4a6bafa9b4e7b55e1fff16818af',
            );

            $this->mmsendmail($post_data);

            $data['code'] = 1;
            $data['msg'] = '发送成功';
            $this->ajaxReturn($data, 'JSON');
            exit;
        } else {
            $data['code'] = 0;
            $data['msg'] = '该邮箱未注册';
            $this->ajaxReturn($data, 'JSON');
            exit;
        }

    }


    public function sendemailcode88()
    {

        $phone = trim(I('post.phone'));

        //$username = '54885782@qq.com';
        //$member = M('Member');
        //$result = $member->where(array('username'=>$username))->find();
        //if($result){
        if (1) {
            $config = M("Config")->find();
            $mycode = rand(100000, 999999);


            //短信接口地址
            $target = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";
            //获取手机号
            $mobile = $phone;
            //生成的随机数
            $mobile_code = $mycode;
            if (empty($mobile)) {
                $data = array();
                $data['code'] = 0;
                $data['msg'] = '手机号码不能为空';
                $this->ajaxReturn($data, 'JSON');
                exit;
            }
            //防用户恶意请求
            //if(empty($_SESSION['send_code']) or $send_code!=$_SESSION['send_code']){
            //	exit('请求超时，请刷新页面后重试');
            //}

            $post_data = "account=" . $config['smsaccount'] . "&password=" . $config['smspass'] . "&mobile=" . $mobile . "&content=" . rawurlencode("您的验证码是：" . $mobile_code . "。请不要把验证码泄露给其他人。");
            //用户名是登录ihuyi.com账号名（例如：cf_demo123）
            //查看密码请登录用户中心->验证码、通知短信->帐户及签名设置->APIKEY
            $gets = xml_to_array(Post($post_data, $target));
            if ($gets['code'] == 2) {
                session('emailcode88', $mycode);
                session('emailadd88', $phone);
                $data = array();
                $data['code'] = 1;
                $data['msg'] = '发送成功';
                $this->ajaxReturn($data, 'JSON');
                exit;
            } else {
                $data = array();
                $data['code'] = 0;
                $data['msg'] = '发送失败，' . $gets['msg'];
                $this->ajaxReturn($data, 'JSON');
                exit;
            }


        } else {
            $data = array();
            $data['code'] = 0;
            $data['msg'] = '该邮箱未注册';
            $this->ajaxReturn($data, 'JSON');
            exit;
        }

    }


    public function forgotpwd_act()
    {
        if (!IS_POST) $this->error("非法请求");
        //默认显示添加表单

        if (IS_POST) {

            //如果用户提交数据
            $model = D("Member");

            $username = I('username');
            $checkcode = I('checkcode');
            $password = I('password');
            $repassword = I('repassword');
            if (strlen($username) > 25) {
                $this->error('此邮箱太长，请从新换一个邮箱！');
            }
            if ($checkcode != session('emailcode')) {
                $this->error('验证码不正确！');
            }
            if ($username != session('emailadd')) {
                $this->error('邮箱不正确！');
            }
            if ($password != $repassword) {
                $this->error('两次密码输入不一致！');
            }
            $user = $model->where(array('username' => $username))->find();
            $data = array();
            $data['id'] = $user['id'];
            $data['password'] = md5($password);
            if ($model->save($data)) {
                $this->success("密码修改成功", U('login/index'));
            } else {
                $this->error("密码修改失败");
            }

        }
    }


    //修改手机号
    public function loginphone()
    {
        if (!IS_POST) $this->error("非法请求");
        //默认显示添加表单

        if (IS_POST) {
            $checkcode = I('checkcode88');
            $config = M("Config")->find();

            $phone = I('phone');

            if (strlen($phone) != 11) {
                $this->error('请输入正确的手机号码！');
            }
            if ($checkcode != session('emailcode88')) {
                $this->error('验证码不正确！');
            }
            if ($phone != session('emailadd88')) {
                $this->error('手机号码不正确！');
            }

            //验证账号密码是否正确
            $user = M("Member")->where(array('phone' => $phone))->find();

            if ($user) {
                $member = M('member');
                $nowmmdate = date('Ymd', time());
                //更新登陆信息
                $data = array(
                    'id' => $user['id'],
                    'update_time' => time(),
                    'freedate' => $nowmmdate,
                    'login_ip' => get_client_ip(0, true),
                );
                if ($nowmmdate > $user['freedate']) {
                    $config = M("Config")->find();
                    if ($user['username']) {
                        $everydaynum = $config['freedownnum1'];
                    }
                    if ($user['phone']) {
                        $everydaynum = $config['freedownnum2'];
                    }
                    if ($user['username'] && $user['phone']) {
                        $everydaynum = $config['freedownnum3'];
                    }
                    $data['everydaynum'] = $everydaynum;
                }
                //如果数据更新成功  跳转到后台主页
                if ($member->save($data)) {
                    session('homeId', $user['id']);
                    session('homename', $user['username']);

                    $Ipaddress = M("Ipaddress");
                    $Ipaddress->where(array('tid' => $user['id']))->delete();
                    $this->success("登陆成功");
                }

            } else {

                $config = M("Config")->find();
                $_POST['allowsize'] = $config['allowsize'];
                $_POST['singlesize'] = $config['singlesize'];
                $_POST['uptype'] = $config['uptype'];
                $_POST['tianshu'] = $config['tianshu'];
                $_POST['everydaynum'] = $config['freedownnum2'];
                $_POST['freedate'] = date('Ymd', time());
                unset($_POST['checkcode88']);
                //如果用户提交数据
                $model = D("Member");

                /*
                $todaytime = strtotime(date('Y-m-d',time()));
                $ip = get_client_ip();
                $mmcount = $model->where(" login_ip='".$ip."' and create_time>'".$todaytime."'")->count();
                if($mmcount>=5){
                    $this->error('同一IP地址一天最多可注册5个账号！') ;
                }*/

                $_POST['isggconfig'] = '1';
                if (!$model->create()) {
                    // 如果创建失败 表示验证没有通过 输出错误提示信息
                    $this->error($model->getError());
                    exit();
                } else {
                    $newuserid = $model->add();
                    if ($newuserid) {
                        session('homeId', $newuserid);
                        session('homename', $phone);
                        $this->success("登陆成功");
                    } else {
                        $this->error("注册失败");
                    }
                }


            }

        }

    }


    /**
     * 专题
     */
    public function zhuanti()
    {
        //   $time = date("Y-m-d H:i:s");
        $articles = M('Articles')->where("startTime <= now() and now() < endTime and spare1='0'")->order('ishot desc,upnum desc,startTime desc')->select();

        foreach ($articles as $k => $val) {
            $articles[$k]['qrcode'] = $this->qrcode('http://' . $_SERVER['HTTP_HOST'] . "/e/" . $val['arid'], $val['arid']);
            $articles[$k]['url'] = "http://" . $_SERVER['HTTP_HOST'] . "/e/" . $val['arid'];
            if ($articles[$k]['ishot'] == 1) {
                $articles[$k]['re'] = 'tuijian';
            }
        }
        $this->articles = $articles;
        $this->display();


    }


    public function qrcode($text = 'http://xx.w6cc.com', $tid, $size = '4', $level = 'L', $padding = 2, $logo = true)
    {
        $path = './Public/png/';
        $QR = $path . $tid . '.png';
        vendor("Phpqrcode.phpqrcode");
        \QRcode::png($text, $QR, $level, $size, $padding);
        imagepng($QR);
        return $tid;
    }
}